package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.BehaviorEnum;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-03-29
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {


    /**
     * 根据用户ID 或者 设备ID 获取行为实体（粉丝实体对象）
     *
     * @param userId
     * @param equipmentId
     * @return
     */
    @Override
    public ApBehaviorEntry getEntry(Integer userId, String equipmentId) {
        //1.根据用户ID 获取行为实体
        if (userId != null) {
            LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApBehaviorEntry::getType, BehaviorEnum.BEHAVIOR_ENTRY_TYPE_USER.getVal());
            queryWrapper.eq(ApBehaviorEntry::getEntryId, userId);
            ApBehaviorEntry entry = this.getOne(queryWrapper);
            if (entry != null) {
                return entry;
            } else {
                //新增用户 行为实体
                ApBehaviorEntry insertEntry = new ApBehaviorEntry();
                insertEntry.setType(BehaviorEnum.BEHAVIOR_ENTRY_TYPE_USER.getVal());
                insertEntry.setEntryId(userId.toString());
                this.save(insertEntry);
                return insertEntry;
            }
        }else{
            //2.根据设备ID 获取行为实体
            LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApBehaviorEntry::getType, BehaviorEnum.BEHAVIOR_ENTRY_TYPE_EQUIP.getVal());
            queryWrapper.eq(ApBehaviorEntry::getEntryId, equipmentId);
            ApBehaviorEntry entry = this.getOne(queryWrapper);
            if (entry != null) {
                return entry;
            } else {
                //新增用户 行为实体
                ApBehaviorEntry insertEntry = new ApBehaviorEntry();
                insertEntry.setType(BehaviorEnum.BEHAVIOR_ENTRY_TYPE_EQUIP.getVal());
                insertEntry.setEntryId(userId.toString());
                this.save(insertEntry);
                return insertEntry;
            }
        }
    }
}
